const fse = require('fs-extra');
const { recursionFilePath } = require('./util');
const { logger } = require('./logger');

const fileExt = ".json";
const targetPathList = [
    "../build/res",
    "../build/wechatgame/res",
];

function replaceContent(content = "") {
    return content.replace(/5@6/g, "7@30").replace(/5@8/g, "7@37");
}

/**
 * 递归格式化对象
 * @param {string} target 
 * @returns 
 */
function recursionFormatObject(target) {
    if (!target) return;

    if (Array.isArray(target)) {
        target.forEach(item => recursionFormatObject(item));
        return target;
    }

    if (target.__type__ !== "cc.Texture2D" && target.type !== "cc.Texture2D") return;

    try {
        if (target.data) {
            target.data = replaceContent(target.data);
        }

        if (target.content) {
            target.content = replaceContent(target.content);
        }
    } catch (error) {
        logger.error(`override file error`, target.data, error);
    }

    return target;
}

/**
 * 格式化文件
 * @param {string} filePath 
 * @returns 
 */
function formatFile(filePath) {
    if (!filePath.endsWith(fileExt)) return;

    const content = fse.readFileSync(filePath, 'utf8');
    try {
        obj = JSON.parse(content);
        const newObj = recursionFormatObject(obj);
        if (!newObj) return;

        fse.writeFileSync(filePath, JSON.stringify(newObj, null, 2), 'utf8');
    } catch (error) {
        logger.error(`override file error ${filePath}`, error);
    }
}

logger.log("format json start");
targetPathList.forEach(targetPath => {
    fse.ensureDirSync(targetPath);
    recursionFilePath(targetPath, formatFile);
});
logger.log("format json done");